import { Map, View } from "ol";
import { ScaleLine, defaults as defaultControls } from "ol/control.js";
import html2canvas from 'html2canvas';
import ZoomSlider from "ol/control/ZoomSlider.js";
import OlExtPrintDialog from "ol-ext/control/PrintDialog";
import {
    Circle as CircleStyle,
    Fill,
    Stroke,
    Style,
    Text,
    Icon,
    Circle,
} from "ol/style";
import { getLength, getArea } from "ol/sphere";
import { Vector as VectorLayer, Heatmap as HeatmapLayer } from "ol/layer";
import { fromLonLat, transform } from "ol/proj";
import Graticule from "ol/layer/Graticule";
import { unByKey } from 'ol/Observable';
import Feature from "ol/Feature";
import Overlay from "ol/Overlay";
import TileLayer from "ol/layer/Tile";
import XYZ from "ol/source/XYZ";
import TileDebug from "ol/source/TileDebug";
import WKT from "ol/format/WKT";
import MultiLineString from "ol/geom/MultiLineString";
import VectorSource from "ol/source/Vector";
import SourceVector from "ol/source/Vector";
import LayerVector from "ol/source/Vector";
import OSM from "ol/source/OSM";
import Point from "ol/geom/Point";
import Polygon from "ol/geom/Polygon";
import Draw from "ol/interaction/Draw";
import SelectInteraction from "ol/interaction/Select";
import LineString from "ol/geom/LineString";
import { Modify, Select } from "ol/interaction";
import { click, platformModifierKeyOnly, shiftKeyOnly } from "ol/events/condition";
import { dataStore } from "../../store/data";
const $store = dataStore();
import { ref } from "vue";
import { ElMessage } from "element-plus";
import $mapreq from '../../api/mapreq';
const map = ref(null);
const lyrList = ref([
    new TileLayer({
        name: "卫星地图",
        visible: true,
        source: new XYZ({
            url: "http://wx.henangis.com/map.aspx?T=JG&z={z}&x={x}&y={y}",
            wrapX: false,
            crossOrigin: 'anonymous'
        }),
    }),
    new TileLayer({
        name: "电子地图1",
        visible: true,
        source: new XYZ({
            url: "http://tdt.yugaosu.com/map.aspx?x={x}&y={y}&l={z}",
            wrapX: false,
            crossOrigin: 'anonymous'
        }),
    }),
    // new TileLayer({
    //     name: "电子地图2",
    //     visible: false,
    //     source: new XYZ({
    //         url: "http://gis.henangis.com/mktxyz.aspx?T=SUPERGIS&z={z}&x={x}&y={y}",
    //         wrapX: false,
    //     }),
    // })
]);
const iconLayer = ref(
    new VectorLayer({
        name: 'icon',
        source: new VectorSource({
            features: [],
        }),
        zIndex: 1000,
        visible: true,
    })
);
var multPOLYGON = ref(
    new VectorLayer({
        source: new VectorSource({ wrapX: false }),
        name: 'multPOLYGON',
        style: new Style({
            fill: new Fill({
                color: 'rgba(0,0,255,0.2)'
            }),
            stroke: new Stroke({
                color: '#FF0000',
                width: 4
            })
        }),
        zIndex: 999
    })
);
const jzwsource = new VectorSource({
    wrapX: false
});
var JZWPOLYGON = ref(
    new VectorLayer({
        source: new VectorSource({
            wrapX: false
        }),
        name: 'JZWPOLYGON',
        style: new Style({
            fill: new Fill({
                color: 'rgba(0,0,255,0.2)'
            }),
            stroke: new Stroke({
                color: '#FFFF00',
                width: 2
            }),
            // text: new Text({
            //     font: '13px Microsoft YaHei',
            //     text: item.name,
            //     fill: new Fill({
            //         color: "yellow"
            //     }),
            // })
        }),
        zIndex: 998,
    })
);
const holesource = new VectorSource({
    wrapX: false
});
const holeLayer = ref(
    new VectorLayer({
        source: holesource,
        name: 'holelayer',
        style: new Style({
            fill: new Fill({
                color: 'rgba(0,0,0,0.2)'
            }),
            stroke: new Stroke({
                color: '#FFFFFF',
                width: 2
            })
        }),
        zIndex: 1001
    })
);
var village = ref(
    new VectorLayer({
        source: jzwsource,
        name: 'village',
        style: new Style({
            fill: new Fill({
                color: 'rgba(0,0,255,0.2)'
            }),
            stroke: new Stroke({
                color: '#FFFFFF',
                width: 1
            })
        }),
        zIndex: 999
    })
);
var resultlayer = ref(
    new VectorLayer({
        source: new VectorSource({
            wrapX: false
        }),
        name: 'resultlayer',
        style: new Style({
            stroke: new Stroke({
                color: '#FF0000',
                width: 2
            })
        }),
        zIndex: 998,
    })
);
var pcxqreslayer = ref(
    new VectorLayer({
        source: new VectorSource({
            wrapX: false
        }),
        name: 'pcxqreslayer',
        style: new Style({
            fill: new Fill({
                color: 'rgba(0,0,255,0.2)'
            }),
            stroke: new Stroke({
                color: '#FFFF00',
                width: 1
            })
        }),
        zIndex: 998,
    })
);
const selectflag = ref(false);
const editlayer = ref(
    new VectorLayer({
        source: new VectorSource({
            wrapX: false
        }),
        name: 'edit',
        style: new Style({
            fill: new Fill({
                color: 'rgba(0,255,255,0.2)'
            }),
            stroke: new Stroke({
                color: '#FF0000',
                width: 2
            })
        }),
        zIndex: 9999
    })
);
const selectLayer = ref(
    new Select({
        // layers:[village.value],
        name: 'select',
        condition: click,
        toggleCondition: shiftKeyOnly,
        addCondition: platformModifierKeyOnly,
        style: new Style({
            fill: new Fill({
                color: 'rgba(255, 255, 0, 0.5)'
            }),
            stroke: new Stroke({
                color: 'rgba(255, 255, 0, 1.0)',
                //lineDash: [10, 10],
                width: 2
            }),
            image: new Circle({
                radius: 5,
                stroke: new Stroke({
                    color: 'rgba(0, 0, 0, 0.7)'
                }),
                fill: new Fill({
                    color: 'rgba(255, 255, 255,0.2)'
                })
            })
        }),
        multi: true,
    })
);

const villageselectLayer = ref(
    new Select({
        // layers:[village.value],
        name: 'select',
        condition: click,
        toggleCondition: shiftKeyOnly,
        addCondition: platformModifierKeyOnly,
        filter: (feature, layer) => {
            return feature.values_.type === 'village';
        },
        style: new Style({
            fill: new Fill({
                color: 'rgba(255, 255, 0, 0.5)'
            }),
            stroke: new Stroke({
                color: 'rgba(255, 255, 0, 1.0)',
                //lineDash: [10, 10],
                width: 2
            }),
            image: new Circle({
                radius: 5,
                stroke: new Stroke({
                    color: 'rgba(0, 0, 0, 0.7)'
                }),
                fill: new Fill({
                    color: 'rgba(255, 255, 255,0.2)'
                })
            })
        }),
        multi: true,
    })
);
const osmlayer = ref(
    new TileLayer({
        source: new OSM()
    })
);
const cutsource = new VectorSource({
    wrapX: false
});
const cutdraw = ref(
    new Draw({
        source: cutsource,
        type: "Polygon",
        style: new Style({
            fill: new Fill({
                color: 'rgba(255, 0, 0, 0.3)'
            }),
            stroke: new Stroke({
                color: 'rgba(255, 0, 0, 1.0)',
                lineDash: [10, 10],
                width: 2
            }),
            image: new Circle({
                radius: 5,
                stroke: new Stroke({
                    color: 'rgba(0, 0, 0, 0.7)'
                }),
                fill: new Fill({
                    color: 'rgba(255, 255, 255, 0.2)'
                })
            })
        })
    })
);
const drawhole = ref(
    new Draw({
        source: holesource,
        type: "Polygon",
        style: new Style({
            fill: new Fill({
                color: 'rgba(0, 0, 0, 0.3)'
            }),
            stroke: new Stroke({
                color: 'rgba(255, 255,255, 1.0)',
                lineDash: [10, 10],
                width: 2
            }),
            image: new Circle({
                radius: 5,
                stroke: new Stroke({
                    color: 'rgba(0, 0, 0, 0.7)'
                }),
                fill: new Fill({
                    color: 'rgba(255, 255, 255, 0.2)'
                })
            })
        })
    })
);
const cutlayer = ref(
    new VectorLayer({
        source: cutsource,
        name: 'cutarea',
        style: new Style({
            fill: new Fill({
                color: 'rgba(255, 0, 0, 0.3)'
            }),
            stroke: new Stroke({
                color: 'rgba(255, 0, 0, 1.0)',
                width: 2
            }),
            image: new Circle({
                radius: 5,
                stroke: new Stroke({
                    color: 'rgba(0, 0, 0, 0.7)'
                }),
                fill: new Fill({
                    color: 'rgba(255, 255, 255, 0.2)'
                })
            })
        })
    })
);
const addsource = new VectorSource({
    wrapX: false
});
const adddraw = ref(
    new Draw({
        source: addsource,
        type: "Polygon",
        style: new Style({
            fill: new Fill({
                color: 'rgba(0, 255, 0, 0.3)'
            }),
            stroke: new Stroke({
                color: 'rgba(255, 0, 0, 1.0)',
                lineDash: [10, 10],
                width: 1
            }),
            image: new Circle({
                radius: 5,
                stroke: new Stroke({
                    color: 'rgba(0, 0, 0, 0.7)'
                }),
                fill: new Fill({
                    color: 'rgba(255, 255, 255, 0.2)'
                })
            })
        })
    })
);
const addlayer = ref(
    new VectorLayer({
        source: addsource,
        name: 'addvillage',
        style: new Style({
            fill: new Fill({
                color: 'rgba(0, 255, 0, 0.3)'
            }),
            stroke: new Stroke({
                color: 'rgba(255, 0, 0, 1.0)',
                width: 1
            }),
            image: new Circle({
                radius: 5,
                stroke: new Stroke({
                    color: 'rgba(0, 0, 0, 0.7)'
                }),
                fill: new Fill({
                    color: 'rgba(255, 255, 255, 0.2)'
                })
            })
        }),
    })
);
export function unloadMap() {
    if (map.value) {
        map.value.setTarget(null);
        map.value.dispose();
        mapreset();       // 释放地图占用的资源
        map.value = null;
    }
}
var overlay1 = ref()
export function init() {
    map.value = new Map({
        // controls: defaultControls().extend([scaleControl]),
        target: "map",
        view: new View({
            center: fromLonLat([114, 34]),
            maxZoom: 18,
            minZoom: 7,
            zoom: 7.9,
            projection: "EPSG:3857",
            //1.设置缩放级别为整数
            constrainResolution: false,
            //2.关闭无级缩放地图
            smoothResolutionConstraint: false,
            extent: [
                11848863.066288825, 3615362.365218805,
                13534939.39251624, 4432710.195185588
            ],
        }),
        controls: defaultControls().extend([new ZoomSlider()]),
    });

    var graticule = new Graticule({
        strokeStyle: new Stroke({
            color: "#FFAAD2",
            width: 1,
            lineDash: [0.5, 4],
        }),
        showLabels: true,
    });


    // map.value.addInteraction(modify_building.value);
    map.value.addLayer(multPOLYGON.value);
    map.value.addLayer(JZWPOLYGON.value);
    map.value.addLayer(village.value);
    map.value.addLayer(iconLayer.value);
    map.value.addLayer(resultlayer.value);
    map.value.addLayer(pcxqreslayer.value);
    map.value.addLayer(holeLayer.value);
    map.value.addLayer(editlayer.value);
    graticule.setMap(map.value);

    lyrList.value.forEach((element) => {
        map.value.addLayer(element);
    });
    overlay1.value = new Overlay({
        //设置弹出框的容器
        element: document.getElementById("popup"),
        positioning: "bottom-center",
        autoPan: false,
        stopEvent: false,//非常重要,如不加上则无法显示,具体和ol-overlaycontainer-stopeven类名有关,详见https://zhuanlan.zhihu.com/p/93134702
        offset: [70,0],
        autoPanAnimation: {
            duration: 250
        }
    });
    map.value.addOverlay(overlay1.value);

    map.value.on('contextmenu', (e) => {
        e.preventDefault();
    })
    map.value.on('pointermove', (e) => {
        const coords = e.coordinate;
        const coordinate = transform(coords, 'EPSG:3857', 'EPSG:4326');
        const longitude = coordinate[0];
        const latitude = coordinate[1];
        $store.curlon = longitude;
        $store.curlat = latitude;

    });
    map.value.on('moveend', (e) => {
        let view = map.value.getView();
        const resolution = view.getResolution();
        const mpu = view.getProjection().getMetersPerUnit();
        let scale = resolution * mpu;
        $store.scale = scale;
    })
    // addpop();
    // console.log(map.value.getLayers(),'map');
}

export function closePopup() {
    overlay1.value.setPosition(undefined); // setPosition 传入undefined会隐藏弹窗元素
}
export function addpop(type) {
    
    //拿到弹出框关闭元素
    map.value.on('click', (e) => {
        let grad = localStorage.getItem('grade');
        let pixel = map.value.getEventPixel(e.originalEvent);
        map.value.forEachFeatureAtPixel(pixel, function (feature) {
            if (grad == '4') {
                return;
            } else {
                var content = ref(document.getElementById("popup-content"));
                var attr = feature.getProperties();
                var coodinate = e.coordinate;
                content.value.innerHTML = "<div>" +
                    '<div>'+type+'名称: ' + attr.name + '</div>' +
                    '<div>'+type+'编号:' + attr.gid + '</div>' +
                    "</div>";
                overlay1.value.setPosition(coodinate);
            }
        })
    })
}

let measureType = 'diatence'; //类型
let draw = ref(null);
let vectorLayer = ref(null);
let tipDiv = ref(null);
let pointermoveEvent = null; // 地图pointermove事件
let sketchFeature = null; // 绘制的要素
let geometryListener = null; // 要素几何change事件
let measureResult = "0"; // 测量结果

const creatDraw = (type) => {
    let maxPoints = null;
    if (measureType == "angle") maxPoints = 3;
    else maxPoints = null;

    // 矢量图层源
    let vectorSource = new VectorSource({
        wrapX: false
    });
    // 矢量图层
    vectorLayer.value = new VectorLayer({
        source: vectorSource,
        style: new Style({
            fill: new Fill({
                color: 'rgba(46, 198, 255, 0.2)'
            }),
            stroke: new Stroke({
                color: '#2ec6ff',
                width: 3
            }),
            image: new Circle({
                radius: 0,
                fill: new Fill({
                    color: '#2ec6ff'
                })
            })
        })
    });
    map.value.addLayer(vectorLayer.value);
    draw.value = new Draw({
        source: vectorSource,
        type: type,
        maxPoints: maxPoints,
        style: new Style({
            fill: new Fill({
                color: 'rgba(46, 198, 255, 0.2)'
            }),
            stroke: new Stroke({
                color: '#2ec6ff',
                lineDash: [10, 10],
                width: 3
            }),
            image: new Circle({
                radius: 0,
                fill: new Fill({
                    color: '#2ec6ff'
                })
            })
        }),
        // 绘制时点击处理事件tipDiv.value
        condition: (evt) => {
            // 测距时添加点标注
            if (measureResult != "0" && !map.value.getOverlayById(measureResult) && measureType == "distence")
                creatMark(null, measureResult, measureResult).setPosition(evt.coordinate);
            return true;
        }
    });
    map.value.addInteraction(draw.value);

    /**
     * 绘制开始事件
     */
    draw.value.on("drawstart", (e) => {
        sketchFeature = e.feature;
        let proj = map.value.getView().getProjection();
        //******距离测量开始时*****//
        if (measureType == "distence") {
            creatMark(null, "起点", "start").setPosition(map.value.getCoordinateFromPixel(e.target.downPx_));
            tipDiv.value.innerHTML = "总长：0 m</br>单击确定地点，双击结束";
            geometryListener = sketchFeature.getGeometry().on('change', (evt) => {
                measureResult = distenceFormat(getLength(evt.target, { "projection": proj, "radius": 6378137 }));
                tipDiv.value.innerHTML = "总长：" + measureResult + "</br>单击确定地点，双击结束";
            });
        }
        //******面积测量开始时*****//
        else if (measureType == "area") {
            tipDiv.value.innerHTML = "面积：0 m<sup>2</sup></br>继续单击确定地点";
            geometryListener = sketchFeature.getGeometry().on('change', (evt) => {
                if (evt.target.getCoordinates()[0].length < 4) tipDiv.value.innerHTML = "面积：0m<sup>2</sup></br>继续单击确定地点";
                else {

                    measureResult = formatArea(getArea(evt.target, { "projection": proj, "radius": 6378137 }));
                    tipDiv.value.innerHTML = "面积：" + measureResult + "</br>单击确定地点，双击结束";
                }
            });
        }
        //******角度测量开始时*****//
        else if (measureType == "angle") {
            tipDiv.value.innerHTML = "继续单击确定顶点";
            geometryListener = sketchFeature.getGeometry().on('change', (evt) => {
                if (evt.target.getCoordinates().length < 3) tipDiv.value.innerHTML = "继续单击确定顶点";
                else {
                    measureResult = formatAngle(evt.target);
                    tipDiv.value.innerHTML = "角度：" + measureResult + "</br>继续单击结束";
                }
            });
        }
    });

    /**
     * 绘制结束事件
     */
    draw.value.on("drawend", (e) => {
        let closeBtn = document.createElement('span');
        closeBtn.innerHTML = "×";
        closeBtn.title = "清除测量";
        closeBtn.style = `
      width: 20px;
      height:20px;
      color:#000;
      line-height: 12px;
      text-align: center;
      border-radius: 50%;
      display: inline-block;
      padding: 2px;
      color: rgb(46, 198, 255);
      border: 2px solid rgb(46, 198, 255);
      background-color: rgb(255, 255, 255);
      font-weight: 600;
      position: absolute;
      top: -36px;
      right: -17px;
      font-size: 15px;
      cursor: pointer;`;
        closeBtn.addEventListener('click', () => {
            clearMeasure();
        });
        //******距离测量结束时*****//
        if (measureType == "distence") {
            creatMark(closeBtn, null, "close1").setPosition(e.feature.getGeometry().getLastCoordinate());
            creatMark(null, "总长：" + measureResult + "", "length").setPosition(e.feature.getGeometry().getLastCoordinate());
            map.value.removeOverlay(map.value.getOverlayById(measureResult));
        }
        //******面积测量结束时*****//
        else if (measureType == "area") {
            let ft = e.feature;
            let geom = ft.getGeometry();
            let arr = geom.getCoordinates()[0];
            let codarr = [];
            codarr = arr.filter((ele, ind) => ind > 0);
            creatMark(closeBtn, null, "close2").setPosition(e.feature.getGeometry().getInteriorPoint().getCoordinates());
            creatMark(null, "总面积：" + measureResult + "", "area").setPosition(e.feature.getGeometry().getInteriorPoint().getCoordinates());
        }
        //******角度测量结束时*****//
        else if (measureType == "angle") {
            creatMark(closeBtn, null, "close3").setPosition(e.feature.getGeometry().getCoordinates()[1]);
            creatMark(null, "角度：" + measureResult + "", "angle").setPosition(e.feature.getGeometry().getCoordinates()[1]);
        }
        // 停止测量
        stopMeasure();
    });
};
// 测量
export function measure(type) {
    if (draw.value != null) return false; // 防止在绘制过程再创建测量
    measureType = type;
    if (vectorLayer.value != null) clearMeasure();
    tipDiv.value = document.createElement('div');
    tipDiv.value.innerHTML = '单击确定起点';
    tipDiv.value.className = "tipDiv.value";
    tipDiv.value.style = `
    width:auto;
    height:auto;
    color:#000;
    padding:4px;
    border:1px solid #2ec6ff;
    font-size:12px;
    background-color:#fff;
    position:relative;
    top:60%;
    left:60%;
    font-weight:600;`;

    let overlay = new Overlay({
        element: tipDiv.value,
        autoPan: false,
        positioning: "bottom-center",
        id: "tipLay",
        stopEvent: false //停止事件传播到地图
    });
    map.value.addOverlay(overlay);

    pointermoveEvent = map.value.on("pointermove", (evt) => {
        overlay.setPosition(evt.coordinate);
    });
    if (measureType == "distence" || measureType == "angle") {
        creatDraw("LineString");
    }
    else if (measureType == "area") {
        creatDraw("Polygon");
    }
}

// 创建标记
const creatMark = (markDom, txt, idstr) => {
    if (markDom == null) {
        markDom = document.createElement('div');
        markDom.innerHTML = txt;
        markDom.style = `
      width:auto;
      height:auto;
      color:#000;
      padding:4px;
      border:1px solid #2ec6ff;
      font-size:12px;
      background-color:#fff;
      position:relative;
      top:60%;
      left:60%;
      font-weight:600;`;
    }
    let overlay = new Overlay({
        element: markDom,
        autoPan: false,
        positioning: "bottom-center",
        id: idstr,
        stopEvent: false
    });
    map.value.addOverlay(overlay);
    return overlay;
};
// 格式化距离结果输出
const distenceFormat = (length) => {
    let output;
    if (length > 100) {
        output = (Math.round(length / 1000 * 100) / 100) + ' ' + 'km'; //换算成km单位
    } else {
        output = (Math.round(length * 100) / 100) + ' ' + 'm'; //m为单位
    }
    return output;//返回线的长度
};
// 格式化面积输出
const formatArea = (area) => {
    let output;
    if (area > 10000) {
        output = (Math.round(area / 1000000 * 100) / 100) + ' ' + 'km<sup>2</sup>'; //换算成km单位
    } else {
        output = (Math.round(area * 100) / 100) + ' ' + 'm<sup>2</sup>';//m为单位
    }
    return output; //返回多边形的面积
};
// 计算角度输出
const formatAngle = (line) => {
    var coordinates = line.getCoordinates();
    var angle = '0°';
    if (coordinates.length == 3) {
        const disa = getLength(new Feature({
            geometry: new LineString([coordinates[0], coordinates[1]])
        }).getGeometry(), {
            radius: 6378137,
            projection: map.value.getView().getProjection()
        });

        const disb = getLength(new Feature({
            geometry: new LineString([coordinates[1], coordinates[2]])
        }).getGeometry(), {
            radius: 6378137,
            projection: map.value.getView().getProjection()
        });

        const disc = getLength(new Feature({
            geometry: new LineString([coordinates[0], coordinates[2]])
        }).getGeometry(), {
            radius: 6378137,
            projection: map.value.getView().getProjection()
        });
        var cos = (disa * disa + disb * disb - disc * disc) / (2 * disa * disb); // 计算cos值
        angle = (Math.acos(cos) * 180) / Math.PI; // 角度值
        angle = angle.toFixed(2); // 结果保留两位小数
    }
    if (isNaN(angle)) return "0°";
    else return angle + "°"; // 返回角度
};
// 停止测量
const stopMeasure = () => {
    tipDiv.value = null;
    map.value.removeInteraction(draw.value); // 移除绘制组件
    draw.value = null;
    map.value.removeOverlay(map.value.getOverlayById("tipLay")); // 移除动态提示框
};
// 清除测量
const clearMeasure = () => {
    vectorLayer.value.getSource().clear();
    map.value.getOverlays().clear();
    //移除监听事件
    unByKey(pointermoveEvent); // 清除鼠标在地图的pointermove事件
    unByKey(geometryListener); // 清除绘制图像change事件
    pointermoveEvent = null;
    geometryListener = null;
    measureResult = "0";
};
// 重置
const resetMeasure = () => {
    if (draw.value != null) stopMeasure();
    if (vectorLayer.value != null) clearMeasure();
};
//转POINT为经纬度数组
export function formatPoint(data) {
    let format = data.replace("POINT(", "");
    format = format.replace(")", "");
    let lonlat = [];
    let x = format.split(" ")[0] / 20037508.34 * 180;
    let y = format.split(" ")[1] / 20037508.34 * 180;
    y = 180 / Math.PI * (2 * Math.atan(Math.exp(y * Math.PI / 180)) - Math.PI / 2);
    lonlat[0] = x;
    lonlat[1] = y;
    return lonlat;
}
//定位
export function aimto(geom) {
    map.value.getView().animate({
        center: fromLonLat(geom),
        zoom: 16,
        duration: 1000
    });
}
export function exportmap() {
    var dom = document.getElementById('map');
    const exportOptions = {
        // 允许跨域
        useCORS: true,
        // 忽略不输出
        ignoreElements: function (element) {
            const className = element.className || '';

        },
    };
    html2canvas(dom, exportOptions).then(function (canvas) {
        var url = canvas.toDataURL("image/jpeg");
        // console.log(url);
        var a = document.createElement('a');
        var event = new MouseEvent('click');
        // 指定下载图片的名称
        a.download = (new Date()).getTime() + ".jpg";
        a.href = url;
        // 触发超链接的点击事件
        a.dispatchEvent(event);
    })
}
export function zoomin() {
    let view = map.value.getView();
    let zoom = view.getZoom();
    view.setZoom(zoom + 1);
}
export function zoomout() {
    let view = map.value.getView();
    let zoom = view.getZoom();
    view.setZoom(zoom - 1);
}

export function loadPOLYGON(name, data, gid) {
    let m_layer = getLayerByName('multPOLYGON');
    if (m_layer) {
        m_layer.getSource().clear();
    }
    var format = new WKT();
    var feature = format.readFeature(data);
    feature.set("name", name);
    feature.set("gid", gid);
    m_layer.getSource().addFeature(feature);
}
export function clearJZW() {
    let m_layer = getLayerByName('JZWPOLYGON');
    let m_village = getLayerByName('village');
    let m_mult = getLayerByName('multPOLYGON');
    if (m_layer) {
        m_layer.getSource().clear();
    }
    if (m_village) {
        m_village.getSource().clear();
    }
    if (m_mult) {
        m_mult.getSource().clear();
    }
}
export function aimWKT(wkt) {
    var format = new WKT();
    var geom = format.readGeometry(wkt);
    map.value.getView().fit(geom.getExtent());
    let view = map.value.getView();
    var zoom = view.getZoom();
    view.animate({
        zoom: zoom + 1
    });
}
export function addvillage(name, data, gid) {
    let m_village = getLayerByName('village');
    var format = new WKT();
    var feature = format.readFeature(data);
    feature.set("name", name);
    feature.set("type", "village");
    feature.set("gid", gid);
    feature.setStyle(
        new Style({
            fill: new Fill({
                color: 'rgba(0,0,255,0.2)'
            }),
            stroke: new Stroke({
                color: '#FFFFFF',
                width: 1
            }),
            text: new Text({
                font: '13px Microsoft YaHei',
                text: name,
                fill: new Fill({
                    color: "red"
                }),
                stroke: new Stroke({
                    color: '#ffffff',
                    width: 3
                }),
            })
        }))
    m_village.getSource().addFeature(feature);
}

// item.name, item.geom, item.code
export function jzwPOLYGON(data) {
    let m_layer = getLayerByName('JZWPOLYGON');
    let jzw = [];
    data.forEach((item, index) => {
        if (!item.geom) {
            return;
        }
        var format = new WKT();
        var feature = format.readFeature(item.geom);
        let name = item.name ? item.name : item.buildname;
        feature.set("name", name);
        feature.set("type", "area");
        feature.setStyle(
            new Style({
                fill: new Fill({
                    color: 'rgba(0,0,255,0.2)'
                }),
                stroke: new Stroke({
                    color: '#FFFF00',
                    width: 2
                }),
                text: new Text({
                    font: '13px Microsoft YaHei',
                    text: item.name ? item.name : item.buildname,
                    fill: new Fill({
                        color: "red"
                    }),
                    stroke: new Stroke({
                        color: '#ffffff',
                        width: 3
                    }),
                })
            })
        )
        if (item.gid) {
            feature.set("gid", item.gid);
        } else {
            feature.set("gid", item.code);

        }
        jzw.push(feature)
    })
    m_layer.getSource().addFeatures(jzw);
    map.value.getView().fit(m_layer.getSource().getExtent());
}

export function drawresultlayer(name, data, gid) {
    let m_layer = getLayerByName('resultlayer');
    var format = new WKT();
    var feature = format.readFeature(data);
    feature.set("name", name);
    feature.set("type", "xzres");
    feature.set("gid", gid);
    m_layer.getSource().addFeature(feature);
    map.value.getView().fit(m_layer.getSource().getExtent());
}
export function drawpcxqres(data) {
    //item.name, item.geom, item.gid
    let m_layer = getLayerByName('pcxqreslayer');
    let features = [];
    var format = new WKT();
    data.forEach((item, index) => {
        if (item.geom) {
            var feature = format.readFeature(item.geom);
            feature.set("name", item.name);
            feature.set("type", "xqres");
            feature.set("gid", item.gid);
            features.push(feature);
        }
    })
    m_layer.getSource().addFeatures(features);
}
function getLayerByName(name) {
    let allLayers = map.value.getLayers().getArray();
    let layer = undefined;
    if (allLayers.length) {
        for (let i = 0; i < allLayers.length; i++) {
            if (allLayers[i].get('name') === name) {
                layer = allLayers[i];
                break;
            }
        }
    }
    return layer;
}
export function addPOINT(name, code, coordinate, imgsize = 16, fontcolor = "yellow", fontsize = 14, remove = false) {
    let m_layer = getLayerByName('icon');
    if (m_layer && remove) {
        m_layer.getSource().clear();
    }
    let embryo = null;
    if (Array.isArray(coordinate)) {
        embryo = new Feature({
            geometry: new Point(fromLonLat(coordinate)),
        });
    } else {
        let format = new WKT();
        let geom = format.readGeometry(coordinate);
        embryo = new Feature({
            geometry: geom,
        });
    }
    embryo.set("code", code);
    embryo.setStyle(
        new Style({
            image: new Icon({
                src: '/ico/online.png',
                width: imgsize,
                height: imgsize,
            }),
            text: new Text({
                text: name,
                font: `${fontsize}px font-size`,
                fill: new Fill({
                    // 设置字体颜色
                    color: fontcolor,
                }),
                stroke: new Stroke({
                    color: '#ffffff',
                    width: 3
                }),
                offsetY: -imgsize - 13, // 设置文字偏移量
            })
        })
    );
    m_layer.getSource().addFeature(embryo);
    if (remove) {
        aimto(formatPoint(coordinate));
    } else {

    }
}
export function aimPoint(coordinate) {
    aimto(formatPoint(coordinate));
}
export function getgeom() {
    map.value.on("singleclick", (e) => {
        let coord = `POINT(${e.coordinate[0]} ${e.coordinate[1]})`;
        addPOINT($store.name, $store.code, coord, 16, 'red', 14, true);
        $store.checkgeo = coord;
    });
}

const seletedarea = ref([]);
export function choose() {
    map.value.addInteraction(selectLayer.value);
    const interactions = map.value.getInteractions().getArray();
    interactions.forEach(interaction => {
        // map.value.removeInteraction(interaction);

    });
    console.log(interactions, 'interactions');
}
export function villagechoose() {
    map.value.addInteraction(villageselectLayer.value);
}
export function union() {
    return seletedarea.value;
}

export function drawcutarea() {
    map.value.addLayer(cutlayer.value);
    map.value.addInteraction(cutdraw.value);
    map.value.removeInteraction(selectLayer.value);
}
const villagecode = ref('');
export function drawaddvillage(e) {
    villagecode.value = e;
    map.value.addLayer(addlayer.value);
    map.value.addInteraction(adddraw.value);
}
//选取
selectLayer.value.on('select', (e) => {
    seletedarea.value = [];
    getLayerByName('edit').getSource().clear();
    e.target.getFeatures().getArray().forEach(item => {
        seletedarea.value.push(item);
    });
});
const villagesel = ref([]);
villageselectLayer.value.on('select', (e) => {
    villagesel.value = [];
    e.target.getFeatures().getArray().forEach(item => {
        villagesel.value.push(item);
    });
});
export function villagedel() {
    return villagesel.value;
}
//绘制裁剪
cutdraw.value.on('drawend', (e) => {
    map.value.removeInteraction(cutdraw.value);
    map.value.addInteraction(selectLayer.value);
});

adddraw.value.on('drawend', (e) => {
    map.value.removeInteraction(adddraw.value);
    setTimeout(() => {
        f_cc();
    }, 200);
});
const m_modify = ref(null);
export function modify() {
    m_modify.value = new Modify({
        source: cutsource
    });
    map.value.addInteraction(m_modify.value);
}
const jzw_modify = ref(new Modify({
    source: jzwsource
}));
export function jzwmodify() {
    map.value.addInteraction(jzw_modify.value);
}
jzw_modify.value.on('modifyend', (e) => {
    updatejzw(e);
});
function updatejzw(e) {
    let geom = 'MULTIPOLYGON(((';
    let coordarr = e.features.item(0).getGeometry().getCoordinates()[0];
    let str = '';
    coordarr[0].forEach((item, index) => {
        str += item.toString().replace(/,/g, ' ') + ',';
    });
    geom += str.slice(0, -1) + ")))";
    let obj = {};
    obj.gid = e.features.item(0).values_.gid;
    obj.geom = geom;
    $mapreq.updateJZW(obj).then(res => {
        if (res.code == 200) {
            ElMessage({
                message: '操作成功!',
                type: 'success'
            });
        }
    });
}
export function f_cc() {
    let addvillage = getLayerByName('addvillage');
    let geom = 'MULTIPOLYGON(((';
    let m_ft = addlayer.value.getSource().getFeatures()[0];
    let coordarr = m_ft.getGeometry().getCoordinates()[0];
    let str = '';
    coordarr.forEach((item, index) => {
        str += item.toString().replace(/,/g, ' ') + ',';
    });
    geom += str.slice(0, -1) + ")))";
    //添加建筑物接口
    let obj = {};
    obj.geom = geom;
    obj.code = localStorage.getItem('jzwlscode');
    $mapreq.addJZW(obj).then(res => {
        if (res.code == 200) {
            ElMessage({
                message: '操作成功!',
                type: 'success'
            });
            if (addvillage) {
                addvillage.getSource().clear();
            }
        }
    });
}

const cutgeom = ref('MULTIPOLYGON(((');
export function cut() {
    cutgeom.value = 'MULTIPOLYGON(((';
    let obj = {};
    obj.area = seletedarea.value;
    if (!getLayerByName('cutarea')) {
        obj.geom = 'MULTIPOLYGON((()))';
    } else {
        let m_ft = cutlayer.value.getSource().getFeatures()[0];
        let coordarr = m_ft.getGeometry().getCoordinates()[0];
        let str = '';
        coordarr.forEach((item, index) => {
            str += item.toString().replace(/,/g, ' ') + ',';
        });
        cutgeom.value += str.slice(0, -1) + ")))";
        obj.geom = cutgeom.value;
    }
    return obj;
    // console.log(cutgeom.value,seletedarea.value);
}
let m_code;
export function makehole(code) {
    m_code = code;

    map.value.addInteraction(drawhole.value);
}
drawhole.value.on('drawend', (e) => {
    setTimeout(() => {
        getholemsg();
    }, 200);
    map.value.removeInteraction(drawhole.value);
});
export function removehole() {
    let obj = {};
    console.log(cut().area[0].values_, 'cut');
    obj.gid = cut().area[0].values_.gid;
    obj.index = 0;
    $mapreq.removeHole(obj).then(res => {
        if (res.code == 200) {
            ElMessage({
                message: '操作成功!',
                type: 'success'
            })
            holeLayer.value.getSource().clear();
            // map.value.removeInteraction(selectLayer.value);
        } else {
            ElMessage({
                message: res.message,
                type: 'warning'
            })
        }
    })
}

function getholemsg() {
    let m_ft = holeLayer.value.getSource().getFeatures()[0];
    let coordarr = m_ft.getGeometry().getCoordinates()[0];
    let outarr = [];
    let dataobj = {};
    if (coordarr.length == 0) {
        ElMessage({
            message: '请绘制一个区域!',
            type: 'warning'
        });
    } else {
        dataobj.gid = cut().area[0].values_.gid;
        coordarr.forEach((item, index) => {
            let obj = {};
            obj.x = item[0];
            obj.y = item[1];
            outarr.push(obj)
        })
        dataobj.coordinates = outarr;
        $mapreq.makeHole(dataobj).then(res => {
            if (res.code == 200) {
                ElMessage({
                    message: '操作成功!',
                    type: 'success'
                })
                holeLayer.value.getSource().clear();
                map.value.removeInteraction(selectLayer.value);
                $mapreq.getXZpcxqlist(m_code).then(res => {
                    if (res.code == 200) {
                        mapreset();
                        jzwPOLYGON(res.data);
                    }
                });
            } else {
                ElMessage({
                    message: res.message,
                    type: 'warning'
                })
            }
        })
    }
}
export function mapreset() {
    let icon = getLayerByName('icon');
    let multPOLYGON = getLayerByName('multPOLYGON');
    let JZWPOLYGON = getLayerByName('JZWPOLYGON');
    let village = getLayerByName('village');
    let resultlayer = getLayerByName('resultlayer');

    let pcxqreslayer = getLayerByName('pcxqreslayer');
    let edit = getLayerByName('edit');
    let addvillage = getLayerByName('addvillage');
    let cutarea = getLayerByName('cutarea');
    if (icon) {
        icon.getSource().clear();
    }
    if (multPOLYGON) {
        multPOLYGON.getSource().clear();
    }
    if (JZWPOLYGON) {
        JZWPOLYGON.getSource().clear();
    }
    if (village) {
        village.getSource().clear();
    }
    if (resultlayer) {
        resultlayer.getSource().clear();
    }
    if (pcxqreslayer) {
        pcxqreslayer.getSource().clear();
    }
    if (edit) {
        edit.getSource().clear();
    }
    if (addvillage) {
        addvillage.getSource().clear();
    }
    if (cutarea) {
        cutarea.getSource().clear();
    }
}
